"use client";
import { useParams } from "next/navigation"; // 使用 Next.js 提供的 useParams 钩子
import { Avatar, Button, Card } from "antd";
import Meta from "antd/es/card/Meta";
import Paragraph from "antd/es/typography/Paragraph";
import Title from "antd/es/typography/Title";
import QuestionList from "@/components/QuestionList";
import { getQuestionBankVoWithSimpleByIdUsingGet } from "@/api/questionBankController";
import "./index.css";
import React, { useState, useEffect } from "react";

/**
 * 题库详情页
 * @constructor
 */
export default function BankDetailPage() {
  const params = useParams(); // 获取路由参数
  const [bank, setBank] = useState<API.QuestionBankVO | null>(null); // 状态管理题库信息
  const [loading, setLoading] = useState(true); // 加载状态

  useEffect(() => {
    const fetchBankData = async () => {
      try {
        const questionBankId = params.questionBankId as string; // 明确类型
        if (!questionBankId) throw new Error("缺少 questionBankId 参数");

        const res = await getQuestionBankVoWithSimpleByIdUsingGet({
          id: questionBankId as any,
        });

        setBank(res.data ?? null); // 更新题库信息
      } catch (e: any) {
        console.error("获取题库详情失败，" + e.message);
      } finally {
        setLoading(false); // 结束加载
      }
    };

    fetchBankData();
  }, [params]);

  if (loading) return <div>加载中...</div>; // 加载中提示
  if (!bank) return <div>获取题库详情失败，请刷新重试</div>; // 错误处理

  const firstQuestionId =
    bank.question?.records && bank.question?.records.length > 0
      ? bank.question.records[0]?.id
      : undefined;

  return (
    <div id="bankPage" className="max-width-content">
      <Card>
        <Meta
          avatar={<Avatar src={bank.picture} size={72} />}
          title={
            <Title level={3} style={{ marginBottom: 0 }}>
              {bank.title}
            </Title>
          }
          description={
            <>
              <Paragraph type="secondary">{bank.description}</Paragraph>
              <Button
                type="primary"
                shape="round"
                href={`/bank/${params.questionBankId}/question/${firstQuestionId}`}
                target="_blank"
                disabled={!firstQuestionId}
              >
                开始刷题
              </Button>
            </>
          }
        />
      </Card>
      <div style={{ marginBottom: 16 }} />
      <QuestionList
        questionBankId={Number.parseInt(params.questionBankId as string)}
        questionList={bank.question?.records ?? []}
        cardTitle={`题目列表（${bank.question?.total || 0}）`}
      />
    </div>
  );
}
